import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_mine.dart';
import 'package:flutter_learn_vi/src/bean/bean_user.dart';
import 'package:flutter_learn_vi/src/model/user_model.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import 'mine_addres_persion_info_page.dart';
import 'mine_select_enum.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/17.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
/// 部门通讯录
class MineSelectDepartmentUserPage extends StatefulWidget {
  final MineBeanDepartmentBean departmentBean;
  final MineBean mineBean;
  final MineSelectType mineSelectType;

  const MineSelectDepartmentUserPage({
    Key key,
    this.mineBean,
    this.departmentBean,
    this.mineSelectType = MineSelectType.common,
  }) : super(key: key);

  @override
  _MineSelectDepartmentUserPageState createState() =>
      _MineSelectDepartmentUserPageState();
}

class _MineSelectDepartmentUserPageState
    extends State<MineSelectDepartmentUserPage> with UserModel {
  List<UserBean> _allLlist = [];
  List<UserBean> _themLlist = [];

  ScrollController _scrollController = new ScrollController();

  TextEditingController _textEditingController = new TextEditingController();

  @override
  void initState() {
    super.initState();
    getUserDetails();
    _scrollController.addListener(() {
      double offset = _scrollController.offset;
      double maxOfsset = _scrollController.position.maxScrollExtent;
      if (offset > maxOfsset / 3 * 2) {
        loadingMore();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_isSearch) {
          _isSearch = false;
          _textEditingController.text = "";
          return false;
        }
        return true;
      },
      child: Scaffold(
        body: RefreshIndicator(
          //可滚动组件在滚动时会发送ScrollNotification类型的通知
          notificationPredicate: (ScrollNotification notifation) {
            //该属性包含当前ViewPort及滚动位置等信息
            ScrollMetrics scrollMetrics = notifation.metrics;
            if (scrollMetrics.minScrollExtent == 0) {
              return true;
            } else {
              return false;
            }
          },
          child: NestedScrollView(
            body: buildGridView(),
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              return [
                SliverAppBar(
                  title: Text("部门通讯录"),
                  pinned: true,
                  expandedHeight: 124,
                  flexibleSpace: FlexibleSpaceBar(
                    background: Container(
                      color: Colors.white,
                      padding: EdgeInsets.only(bottom: 12, left: 16, right: 16),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Container(
                            height: 40,
                            padding:
                                EdgeInsets.only(left: 12, right: 12, top: 4),
                            decoration: BoxDecoration(
                                border: Border.all(
                                    color: Colors.blueGrey.withOpacity(0.6)),
                                borderRadius:
                                    BorderRadius.all(Radius.circular(24))),
                            alignment: Alignment.center,
                            child: TextField(
                              controller: _textEditingController,
                              autofocus: false,
                              onChanged: (String value) {
                                searchFunction(value);
                              },
                              decoration: InputDecoration(
                                  hintText: "搜索", border: InputBorder.none),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                )
              ];
            },
          ),
          onRefresh: () async {
            _pageIndex = 1;
            await getUserDetails();
            ToastUtils.showToast("已刷新");
            return true;
          },
        ),
      ),
    );
  }

  Widget buildGridView() {
    if (isLoading) {
      return Center(
        child: LoadingWidget(),
      );
    }
    if (_allLlist.length == 0) {
      return Center(
        child: NoDataWidget(
          clickCallBack: () {
            getUserDetails();
          },
        ),
      );
    }
    if (_isSearch && _themLlist.length == 0) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextButton(
            onPressed: () {
              getUserDetails();
            },
            child: Text("点击搜索更多"),
          )
        ],
      );
    }
    return ListView.builder(
      padding: EdgeInsets.only(top: 10),
      controller: _scrollController,
      itemCount:
      _themLlist.length > 25 ? _themLlist.length + 1 : _themLlist.length,
      itemBuilder: (BuildContext context, int index) {
        if (index == _themLlist.length) {
          return Container(
            height: 44,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "已滑动到底部",
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
          );
        } else {
          return buildListViewItemWidget(index);
        }
      },
    );
  }

  Widget buildListViewItemWidget(int index) {
    UserBean userBean = _themLlist[index];
    return InkWell(
      onTap: () {
        if (widget.mineSelectType == MineSelectType.common) {
          NavigatorUtils.pushPage(
            context,
            MineAddresPersionInfoPage(userBean: userBean),
          );
        } else {
          NavigatorUtils.pop(context, parameters: userBean);
        }
      },
      child: Container(
        margin: EdgeInsets.only(left: 14, right: 14, top: 10),
        padding: EdgeInsets.only(left: 16, top: 10, bottom: 10, right: 12),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(3))),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            buildImage(index),
            SizedBox(
              width: 18,
            ),
            Expanded(
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          "${userBean.reamName}",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 16,
                          ),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Text(
                          "${userBean.userPost}",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 12,
                          ),
                        )
                      ],
                    ),
                  ),
                  Icon(Icons.arrow_forward_ios_rounded)
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildImage(int index) {
    return Container(
      margin: EdgeInsets.only(top: 2),
      child: Text("${index + 1}"),
    );
  }

  bool isLoading = true;
  int _pageIndex = 1;
  bool isLoadingMore = false;

  //加载更多
  void loadingMore() {
    if (!isLoadingMore) {
      isLoadingMore = true;
      _pageIndex++;
      getUserDetails();
    }
  }

  bool _isSearch = false;

  void searchFunction(String title) {
    LogUtils.e("搜索 title $title");
    _themLlist.clear();
    if (title
        .trim()
        .length == 0) {
      _isSearch = false;
      _themLlist.addAll(_allLlist);
    } else {
      _allLlist.forEach((element) {
        String name = element.department;
        if (name.contains(title)) {
          _themLlist.add(element);
        }
      });
      _isSearch = true;
    }
    setState(() {});
  }

  Future<bool> getUserDetails() async {
    String userName = "";
    int pageIndex = _pageIndex;
    if (_isSearch) {
      pageIndex = 1;
      userName = _textEditingController.text;
    }
    //获取
    List<UserBean> userList = await getMineDepartmentUserRequest(
        mineId: widget.mineBean.id,
        pageIndex: pageIndex,
        userName: userName,
        department: widget.departmentBean.department);
    if (_isSearch) {
      if (userList.length > 0) {
        _themLlist = [];
        _themLlist.addAll(userList);
      }
      ToastUtils.showToast("搜索完成");
    } else {
      if (userList.length == 0) {
        if (_pageIndex == 1) {
          _allLlist = userList;
        } else {
          _pageIndex--;
        }
      } else {
        if (_pageIndex == 1) {
          _allLlist = userList;
        } else {
          _allLlist.addAll(userList);
        }
      }
      _themLlist = [];
      _themLlist.addAll(_allLlist);
      isLoadingMore = false;
      isLoading = false;
    }
    if (!mounted) return true;
    setState(() {});
    return Future.value(true);
  }
}
